import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController, ToastController, App } from 'ionic-angular';
import { localbase } from '../../models/localbase';
import { ListMasterPage } from '../list-master/list-master';
import { Api } from "../../providers/api/api";

import { QueOutput, AnswerLog, AnswerLogUp, MobileAnswer, MobileAnserChd } from '../../models/quesinfo';
import { GoonPage } from '../goon/goon';
import { AsyncPipe } from '@angular/common';

/**
 * Generated class for the RecyclingPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-recycling',
  templateUrl: 'recycling.html',
})
export class RecyclingPage {
  @ViewChild('inp') inp: ElementRef;
  @ViewChild('inpover') inpover: ElementRef;
  @ViewChild('inpnot') inpnot: ElementRef;
  @ViewChild('inpstop') inpstop: ElementRef;
  public recylist;
  public _fqid;
  public _list;
  public pepperoni = [];
  public pepperoniover = [];
  public pepperoninot = [];
  public pepperonistop = [];
  public _tname;
  public bug = [];
  public bugover = [];
  public bugnot = [];
  public bugstop = [];
  public zid = [];
  public wid = [];
  public yid = [];
  public allid = [];
  public allse;
  public allseover;
  public allsenot;
  public allsestop;
  public num;
  public numw;
  public numy;
  public numz;
  public numall;
  public ell;
  public all;
  public statusF;
  public resData;
  public _statedata;
  ngOnInit(): void {
    this._fqid = this.navParams.get("fqid");

    this.datas(this._fqid);
  }
  async datas(a) {
    this.allid = [];
    this.zid = [];
    this.wid = [];
    this.yid = [];

    this._list = await this.localbasefun.getbaseAnswerlogByFQId(a);
    this.numw = '0';
    this.numz = '0';
    this.numy = '0';
    this.numall = '0';
    //console.log(this._list)
    if (this._list.length < 1) {
      this._tname = "此问卷没有回收记录";

    } else {
      this._list.forEach(p => {
        p["ispicked"] = false;
      });
      this._tname = this._list[0].FTitle;
      this.num = this._list.length;
      this._list.forEach((item, a) => {
        if (item.FUpdateloadState == -1) {
          let w = {};
          w["z"] = item.FAnswerId + "," + item.FQId;
          this.zid.push(w);
          this.numz = this.zid.length;
        }
        if (item.FUpdateloadState == 1) {

          let w = {};
          w["w"] = item.FAnswerId + "," + item.FQId;
          this.wid.push(w);
          this.numw = this.wid.length;
        }
        if (item.FUpdateloadState == 2) {
          let w = {};
          w["y"] = item.FAnswerId + "," + item.FQId;
          this.yid.push(w);
          this.numy = this.yid.length;
        }
        let w = {};
        w["q"] = item.FAnswerId + "," + item.FQId;
        this.allid.push(w);

        this.numall = this.allid.length
      })
    }
  }

  show = [];
  showover = [];
  shownot = [];
  showstop = [];
  alldele = [];
  alldeleover = [];
  alldelenot = [];
  alldelestop = [];
  deledata = [];
  alldelearr = [];
  alldeleoverarr = [];
  alldelenotarr = [];
  alldelestoparr = [];
  allidc = [];
  widc = [];
  yidc = [];
  zidc = [];
  notnum = 0;
  r = true;
  showControl(i) {
    this.show[i] = !this.show[i]
  }
  showControlover(i) {
    this.showover[i] = !this.showover[i]
  }
  showControlnot(i) {
    this.shownot[i] = !this.shownot[i]
  }
  showControlstop(i) {
    this.showstop[i] = !this.showstop[i]
  }
  questionStatus = 'all';

  constructor(
    public localbasefun: localbase,
    public navCtrl: NavController,
    public navParams: NavParams,
    public alertCtrl: AlertController,
    private api: Api,
    public toastCtrl: ToastController,
    public app: App) {

  }

  ionViewDidLoad() {

  }

  updateCucumber(i, pick, s, t) {
    if (pick) {
      let jion = (s + "," + t)
      this.alldele.push({ q: jion });
    } else {
      if (this.allse = "true") {
        for (var u = 0; u < this.allid.length; u++) {
          if (this.allid[u].q == (s + "," + t)) {
            this.allid.splice(u, 1);
            this.alldele = this.allid;
          }
        }
      }
      for (var u = 0; u < this.alldele.length; u++) {
        if (this.alldele[u].q == (s + "," + t)) {
          this.alldele.splice(u, 1);
        }
      }
    }
    let el: HTMLElement = <HTMLElement>this.inp.nativeElement
    let all = el.querySelectorAll('ion-checkbox')   // NodeList
    let all2 = [].slice.call(el.querySelectorAll('ion-checkbox'))    // Array
    this._list.forEach((item, a) => {
      if (item.ispicked) {
        this.bug.push("a")
      }
    });
    if (this.bug.length == all2.length - 1) {
      this.allse = "true";
    } else {
      this.allse = "false";
    }
    this.bug = [];
  }

  updateCucumberover(i, pick, s, t) {
    if (pick) {
      let jion = (s + "," + t)
      this.alldeleover.push({ y: jion });
    } else {
      if (this.allseover = "true") {
        for (var u = 0; u < this.yid.length; u++) {
          if (this.yid[u].y == (s + "," + t)) {
            this.yid.splice(u, 1);
            this.alldeleover = this.yid;
          }
        }
      }
      for (var u = 0; u < this.alldeleover.length; u++) {
        if (this.alldeleover[u].y == (s + "," + t)) {
          this.alldeleover.splice(u, 1);
        }
      }
    }
    let el: HTMLElement = <HTMLElement>this.inpover.nativeElement
    let all = el.querySelectorAll('ion-checkbox')   // NodeList
    let all2 = [].slice.call(el.querySelectorAll('ion-checkbox'))    // Array
    this._list.forEach((item, a) => {
      if (item.FUpdateloadState == 2) {
        if (item.ispicked) {
          this.bugover.push("a")
        }
      }
    });
    if (this.bugover.length == all2.length - 1) {
      this.allseover = "true";
    } else {
      this.allseover = "false";
    }
    this.bugover = [];
  }
  updateCucumbernot(i, pick, s, t) {
    if (pick) {
      let jion = (s + "," + t)
      this.alldelenot.push({ w: jion });
    } else {
      if (this.allsenot = "true") {
        for (var u = 0; u < this.wid.length; u++) {
          if (this.wid[u].w == (s + "," + t)) {
            this.wid.splice(u, 1);
            this.alldelenot = this.wid;
          }
        }
      }
      for (var u = 0; u < this.alldelenot.length; u++) {
        if (this.alldelenot[u].w == (s + "," + t)) {
          this.alldelenot.splice(u, 1);
        }
      }
    }
    let el: HTMLElement = <HTMLElement>this.inpnot.nativeElement
    let all = el.querySelectorAll('ion-checkbox')   // NodeList
    let all2 = [].slice.call(el.querySelectorAll('ion-checkbox'))    // Array

    this._list.forEach((item, a) => {
      if (item.FUpdateloadState == 1) {
        if (item.ispicked) {
          this.bugnot.push("a")
        }
      }
    });
    if (this.bugnot.length == all2.length - 1) {
      this.allsenot = "true";
    } else {
      this.allsenot = "false";
    }
    this.bugnot = [];
  }
  updateCucumberstop(i, pick, s, t) {
    if (pick) {
      let jion = (s + "," + t)
      this.alldelestop.push({ z: jion });
    } else {
      if (this.allsestop = "true") {
        for (var u = 0; u < this.zid.length; u++) {
          if (this.zid[u].z == (s + "," + t)) {
            this.zid.splice(u, 1);
            this.alldelestop = this.zid;
          }
        }
      }
      for (var u = 0; u < this.alldelestop.length; u++) {
        if (this.alldelestop[u].z == (s + "," + t)) {
          this.alldelestop.splice(u, 1);
        }
      }
    }
    let el: HTMLElement = <HTMLElement>this.inpstop.nativeElement;
    let all = el.querySelectorAll('ion-checkbox')   // NodeList
    let all2 = [].slice.call(el.querySelectorAll('ion-checkbox'))    // Array
    this._list.forEach((item, a) => {
      if (item.FUpdateloadState == -1) {
        if (item.ispicked) {
          this.bugstop.push("a")
        }
      }
    });
    if (this.bugstop.length == all2.length - 1) {
      this.allsestop = "true";
    } else {
      this.allsestop = "false";
    }
    this.bugstop = [];
  }

  allSe(allse) {
    if (allse) {
      this._list.forEach(p => {
        p["ispicked"] = true;
      })
      for (let q = 0; q < this.allid.length; q++) {
        this.allidc.push(this.allid[q]["q"]);
      }
    } else {
      this._list.forEach(p => {
        p["ispicked"] = false;
      })
      this.allidc = [];
    }
  }
  allSeover(allseover) {
    if (allseover) {
      this._list.forEach(p => {
        if (p.FUpdateloadState == 2) {
          p["ispicked"] = true;
        }
      })
      for (let q = 0; q < this.yid.length; q++) {
        this.yidc.push(this.yid[q]["y"]);
      }
    } else {
      this._list.forEach(p => {
        if (p.FUpdateloadState == 2) {
          p["ispicked"] = false;
        }
      })
      this.yidc = [];

    }
  }
  allSenot(allsenot) {
    if (allsenot) {

      this._list.forEach(p => {
        if (p.FUpdateloadState == 1) {
          p["ispicked"] = true;
        }
      })
      for (let q = 0; q < this.wid.length; q++) {
        this.widc.push(this.wid[q]["w"]);
      }
    } else {
      this._list.forEach(p => {
        if (p.FUpdateloadState == 1) {
          p["ispicked"] = false;
        }
      })
      this.widc = [];

    }
  }
  allSestop(allsestop) {
    console.log(this.zid);
    if (allsestop) {
      this._list.forEach(p => {
        if (p.FUpdateloadState == -1) {
          p["ispicked"] = true;
        }
      })
      for (let q = 0; q < this.zid.length; q++) {
        this.zidc.push(this.zid[q]["z"]);
      }
    } else {
      this._list.forEach(p => {
        if (p.FUpdateloadState == -1) {
          p["ispicked"] = false;
        }
      })
      this.zidc = [];

    }
  }
  singledele(I, S, T) {

    let confirm = this.alertCtrl.create({
      title: '确认删除',
      buttons: [
        {
          text: '取消',
          handler: () => {

          }
        },
        {
          text: '确定',
          handler: async () => {
            let data = (S + "," + T);

            await this.localbasefun.delbaseAnswerlog(data);
            if (this.allsestop) {
              this.numz = "0";
            }
            if (this.allsenot) {
              this.numw = "0";
            }
            if (this.allseover) {
              this.numy = "0";
            }
            this.datas(T);
          }
        }
      ]

    });
    confirm.present();
  }
  OnDelete(I, S, T) {
    this.singledele(I, S, T);
  }
  OnDeleteover(I, S, T) {
    this.singledele(I, S, T);
  }
  OnDeletenot(I, S, T) {
    this.singledele(I, S, T);
  }
  OnDeletestop(I, S, T) {
    this.singledele(I, S, T);
  }

  moredele() {
    // const moredele=this.localbasefun;
    // if(this.allse==true){
    //   //console.log(this.allidc)
    //   moredele.delbaseAnswerlogs(this.allidc);
    //   this.allse="false";
    //   this.numall="0";
    // }else{
    //   for(var u=0;u<this._list.length;u++){

    //   }
    //   //console.log(this.alldele)
    //   for(var u=0;u<this.alldele.length;u++){
    //     this.alldelearr.push(this.alldele[u].q)
    //   }
    //   //console.log(this.alldelearr)
    //   moredele.delbaseAnswerlogs(this.alldelearr);
    //   this._list.forEach((item,a)=> {
    //       item.ispicked="false";
    //   })
    if (this.alldele.length > 0 || this.allse == true) {
      let confirm = this.alertCtrl.create({
        title: '确认删除',
        buttons: [
          {
            text: '取消',
            handler: () => {

            }
          },
          {
            text: '确定',
            handler: async () => {
              const moredele = this.localbasefun;
              if (this.allse == true) {
                //console.log(this.allidc)
                await moredele.delbaseAnswerlogs(this.allidc);
                this.allse = "false";
                this.numall = "0";
              } else {
                for (var u = 0; u < this._list.length; u++) {

                }
                //console.log(this.alldele)
                for (var u = 0; u < this.alldele.length; u++) {
                  this.alldelearr.push(this.alldele[u].q)
                }
                //console.log(this.alldelearr)
                await moredele.delbaseAnswerlogs(this.alldelearr);
                this._list.forEach((item, a) => {
                  item.ispicked = "false";
                })
              }
              this.datas(this._fqid);
            }
          }
        ]

      });
      confirm.present();
    } else {
      let toast = this.toastCtrl.create({
        message: "请选择要删除的",
        duration: 1500,
        position: 'top'
      });
      toast.present();
      return false;
    }

  }

  moredeleover() {
    if (this.alldeleover.length > 0 || this.allseover == true) {
      let confirm = this.alertCtrl.create({
        title: '确认删除',
        buttons: [
          {
            text: '取消',
            handler: () => {

            }
          },
          {
            text: '确定',
            handler: () => {
              const moredele = this.localbasefun;
              if (this.allseover == true) {
                moredele.delbaseAnswerlogs(this.yidc);
                this.allseover = "false";
                this.numy = "0";
              } else {
                for (var u = 0; u < this.alldeleover.length; u++) {
                  this.alldeleoverarr.push(this.alldeleover[u].y)
                }
                moredele.delbaseAnswerlogs(this.alldeleoverarr);
                this._list.forEach((item, a) => {
                  if (item.FUpdateloadState == 2) {
                    item.ispicked = "false";
                  }
                })
              }
              this.datas(this._fqid);
            }
          }
        ]

      });

      confirm.present();
    } else {
      let toast = this.toastCtrl.create({
        message: "请选择要删除的",
        duration: 1000,
        position: 'top'
      });
      toast.present();
      return false;
    }

  }


  moredelenot() {
    if (this.alldelenot.length > 0 || this.allsenot == true) {
      let confirm = this.alertCtrl.create({
        title: '确认删除',
        buttons: [
          {
            text: '取消',
            handler: () => {

            }
          },
          {
            text: '确定',
            handler: () => {
              const moredele = this.localbasefun;
              if (this.allsenot == true) {
                moredele.delbaseAnswerlogs(this.widc);
                this.allsenot = "false";
                this.numw = "0";
              } else {
                for (var u = 0; u < this.alldelenot.length; u++) {
                  this.alldelenotarr.push(this.alldelenot[u].w)
                }
                moredele.delbaseAnswerlogs(this.alldelenotarr);
                this._list.forEach((item, a) => {
                  if (item.FUpdateloadState == 1) {
                    item.ispicked = "false";
                  }
                })
              }
              this.datas(this._fqid);
            }
          }
        ]

      });
      confirm.present();
    } else {
      let toast = this.toastCtrl.create({
        message: "请选择要删除的",
        duration: 1000,
        position: 'top'
      });
      toast.present();
      return false;
    }
  }

  moredelestop() {
    if (this.alldelestop.length > 0 || this.allsestop == true) {
      let confirm = this.alertCtrl.create({
        title: '确认删除',
        buttons: [
          {
            text: '取消',
            handler: () => {

            }
          },
          {
            text: '确定',
            handler: async () => {
              const moredele = this.localbasefun;
              if (this.allsestop == true) {
                await moredele.delbaseAnswerlogs(this.zidc);
                this.allsestop = "false";
                this.numz = "0";
              } else {
                for (var u = 0; u < this.alldelestop.length; u++) {
                  this.alldelestoparr.push(this.alldelestop[u].z)
                }
                await moredele.delbaseAnswerlogs(this.alldelestoparr);
                this._list.forEach((item, a) => {
                  if (item.FUpdateloadState == -1) {
                    item.ispicked = "false";
                  }
                })
              }
              this.datas(this._fqid);
            }
          }
        ]

      });

      confirm.present();
    } else {
      let toast = this.toastCtrl.create({
        message: "请选择要删除的",
        duration: 1000,
        position: 'top'
      });
      toast.present();
      return false;
    }

  }
  alldelete() {
    this.moredele();
  }
  alldeleteover() {
    this.moredeleover();
  }
  alldeletenot() {
    this.moredelenot();
  }
  alldeletestop() {
    this.moredelestop();
  }
  recycli(answerid) {
    let param = { FQID: this._fqid };
    this.api.questionnaireAnswers(param).subscribe(res => {
      this.resData = res;
      this.app.getRootNav().push('GoonPage', { resData: <QueOutput>this.resData, s: '1', answerid: answerid })
    });
  }

  /**
   * 继续作答
   * @param answerid
   */
  async goon(answerid) {
    let param = { FQID: this._fqid };
    let localbasefun = this.localbasefun;
    let ss = await this.localbasefun.getQueByFqidEdit(answerid);
    console.log('ss:' + answerid);
    console.log(ss);
    this.navCtrl.push("GoonPage", { resData: <QueOutput>ss, s: '-1', answerid: answerid });
    // this.api.questionnaireAnswers(param).subscribe(res=>{
    //             this.resData = res;
    //    this.navCtrl.push("GoonPage",{resData:<QueOutput>this.resData,s:'-1',answerid:answerid});
    //   //this.navCtrl.push('GoonPage',{resData:<QueOutput>this.resData,stype:'-1',answerid:answerid})
    // });
  }
  //上传按钮
  async UploadBtn() {
    const localbasefun = this.localbasefun;
    let AnswerLogs = new Array<AnswerLog>();
    this._list.forEach((onea, indexa) => {
      //console.log(onea)
      if (onea.FUpdateloadState == 1 && onea.ispicked == true) {
        //
        AnswerLogs.push(onea);
      }
    });
    //console.log(this._list);
    //
    if (AnswerLogs.length > 0) {
      await this.uploadanswerlogs(AnswerLogs);
      this.ngOnInit();
    } else {
      let toast = this.toastCtrl.create({
        message: "请选择要上传的",
        duration: 1500,
        position: 'top'
      });
      toast.present();
      return false;
    }

  }
  //上传
  async uploadanswerlogs(AnswerLogs: Array<AnswerLog>) {
    let isSuccess = true;
    AnswerLogs.forEach(async oneAnswerLog => {
      let tempdata = new AnswerLogUp();
      tempdata.FQId = oneAnswerLog.FQId;
      tempdata.FTitle = oneAnswerLog.FTitle;
      tempdata.FStartTime = oneAnswerLog.FStartTime;
      tempdata.FAnswerId = oneAnswerLog.FAnswerId;
      tempdata.FUpdateloadState = oneAnswerLog.FUpdateloadState;
      tempdata.Gps = oneAnswerLog.Gps;
      tempdata.FSummitTime = oneAnswerLog.FSummitTime;
      //  const localbasefun1=this.localbasefun;
      tempdata.FPersonId = oneAnswerLog.FPersonId;
      tempdata.TopicIdList = oneAnswerLog.TopicIdList;
      //
      tempdata.listTopic = new Array<MobileAnswer>();
      //
      let topiclist = oneAnswerLog.TopicResult;
      topiclist.forEach((onetopic, indext) => {
        if (onetopic.FShow) {
          let oneMobileAnswer = new MobileAnswer("", "", "", [], 0, "", "");
          oneMobileAnswer.FTopicId = onetopic.FTopicId;
          oneMobileAnswer.FTitle = onetopic.FTitle;
          oneMobileAnswer.FType = onetopic.FType;
          oneMobileAnswer.FSoundDuration = onetopic.FAudioLength;
          oneMobileAnswer.FSoundData = onetopic.FAudio;
          oneMobileAnswer.ImgData = onetopic.FImage;
          //
          oneMobileAnswer.longitude = onetopic.longitude;
          oneMobileAnswer.lat = onetopic.lat;
          oneMobileAnswer.Address = onetopic.Address;
          //
          oneMobileAnswer.listChild = new Array<MobileAnserChd>();
          //
          onetopic.listChild.forEach(onelistChild => {
            let oneMobileAnserChd = new MobileAnserChd();
            oneMobileAnserChd.FAnswerChdId = onelistChild.FAnswerChdId;
            oneMobileAnserChd.FQId = onelistChild.FQId;
            oneMobileAnserChd.FTopicId = onelistChild.FTopicId;
            oneMobileAnserChd.FROptionId = onelistChild.FROptionId;
            oneMobileAnserChd.FROptionContent = onelistChild.FROptionContent;
            oneMobileAnserChd.FCOptionId = onelistChild.FCOptionId;
            oneMobileAnserChd.FCOptionContent = onelistChild.FCOptionContent;
            oneMobileAnserChd.FType = onelistChild.FType;
            oneMobileAnserChd.FTextContent = onelistChild.FTextContent;
            oneMobileAnserChd.FTitle = onelistChild.FTitle;
            oneMobileAnserChd.FROptionSort = onelistChild.FROptionSort;
            oneMobileAnserChd.FCOptionSort = onelistChild.FCOptionSort;
            oneMobileAnserChd.FBase64 = onelistChild.FBase64;
            //
            oneMobileAnswer.listChild.push(oneMobileAnserChd);
          });
          //
          tempdata.listTopic.push(oneMobileAnswer);
        }
      });

      //上传
      const code = await this.api.addMobileAnswer(tempdata);
      if (code && code.message === '上传成功') {
        const localbasefun = this.localbasefun; // //改变作答状态
        await this.localbasefun.changeAnswerState(oneAnswerLog.FAnswerId, oneAnswerLog.FQId, oneAnswerLog.FPublishTime, 2);
      } else {
        isSuccess = false;
      }
    });
    if (isSuccess) {
      let confirm = this.alertCtrl.create({
        title: '已上传',
        buttons: [
          {
            text: '确定',
            handler: () => {
              // this.navCtrl.push('ListMasterPage');
              this.ngOnInit();
            }
          }
        ]

      });
      confirm.present();
    } else {
      let toast = this.toastCtrl.create({
        message: "上传失败",
        duration: 1000,
        position: 'top'
      });
      toast.present();
    }
  }
  clearUpladed() {
    let confirm = this.alertCtrl.create({
      title: '确认清空已上传',
      buttons: [
        {
          text: '取消',
          handler: () => {

          }
        },
        {
          text: '确定',
          handler: async () => {
            const localbasefun = this.localbasefun;
            await this.localbasefun.clearUpladedAnswerlog(this._fqid);
            this.ngOnInit();
          }
        }
      ]

    });
    confirm.present();
  }
  doRefresh(refresher) {
    this.ngOnInit();
    // console.log('Begin async operation', refresher);
    // location.reload();
    setTimeout(() => {
      // console.log('Async operation has ended');
      refresher.complete();
    }, 2000);
  }

}
